<template>
  <!-- 首页 -->
  <div class="box">
    <div class="boxitem">
      <div>科目：</div>
      <el-select v-model="subject" placeholder="Select" class="boxitem">
        <el-option
          v-for="item in subjects"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
    </div>
    <div class="boxitem">
      <div>类型：</div>
      <el-select v-model="type" placeholder="Select" class="boxitem" @change="choosetype">
        <el-option
          v-for="item in types"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
    </div>
    <div class="boxitem" v-if="type === '练习'">
      <div>题目数量：</div>
      <el-select v-model="num" placeholder="Select">
        <el-option
          v-for="item in nums"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
    </div>
    <el-button v-if="!isTestpaper" class="btn" type="primary" @click="createNew(0)">继续</el-button>
    <el-button v-if="!isTestpaper" class="btn" @click="createNew(1)">新建</el-button>
    <el-button v-if="isTestpaper" class="btn" type="primary" @click="openDrawer">选择试卷</el-button>
  </div>
  <!-- 组卷对话框 -->
  <el-dialog
    v-model="groupDialog"
    :title="subject + '组卷设计'"
    width="450px"
    :show-close="false"
    @close="closedialo"
  >
      <el-form :model="questionnum" label-width="120px">
        <el-form-item label="单选题量">
          <el-select v-model="questionnum.dannum" placeholder="Select">
            <el-option
              v-for="item in [1,2,3,4,5]"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="多选题量">
          <el-select v-model="questionnum.duonum" placeholder="Select">
            <el-option
              v-for="item in [1,2,3,4,5]"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="判断题量">
          <el-select v-model="questionnum.pannum" placeholder="Select">
            <el-option
              v-for="item in [1,2,3,4,5]"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="填空题量">
          <el-select v-model="questionnum.tiannum" placeholder="Select">
            <el-option
              v-for="item in [1,2,3,4,5]"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="groupcreate">创建组卷</el-button>
          <el-button @click="random">随机题量</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>
  <!-- 试卷列表抽屉 -->
  <el-drawer v-model="drawer" :title="subject + '试卷列表'">
    <el-scrollbar height="500px">
      <div v-for="(item, index) in testpaperlist" :key="item" class="scrollbar-demo-item" @click="changeBtnShow(index)">
        <div class="item">
          <text>{{getNowDate(item.time)}}</text><text>{{item.testpaper}}</text>
        </div>
        <div class="btnbox" v-if="btnShow[index]">
          <el-button @click="testp(item, 1)">新建</el-button>
          <el-button type="primary" @click="testp(item, 0)">继续</el-button>
        </div>
      </div>
    </el-scrollbar>
  </el-drawer>
  <!-- 题目信息对话框 -->
  <div style="text-align: center;">
    <el-button type="primary" style="width: 20%;" @click="dialogVisible = true">上传题目</el-button>
  </div>
  <el-dialog
    v-model="dialogVisible"
    title="编辑题目"
    width="50%"
    :show-close="false"
    @close="closedialo"
  >
      <el-form :model="question" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="问题" prop="title">
          <el-input v-model="question.title" maxlength="50" placeholder="请输入题目" show-word-limit type="textarea"/>
        </el-form-item>
        <el-form-item label="是否新添科目">
          <el-switch v-model="question.isaddsubject" />
        </el-form-item>
        <el-form-item label="科目" v-if="!question.isaddsubject" prop="subject">
          <el-select v-model="question.subject" class="m-2" placeholder="Select">
            <el-option
              v-for="item in subjects"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="新科目" v-if="question.isaddsubject" prop="newsubject">
          <el-input v-model="question.newsubject" placeholder="请输入新科目英文"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="question.type" class="m-2" placeholder="Select" @change="changeSelectType">
            <el-option
              v-for="item in [
                { label: '多选题', value: 'duo' },
                { label: '单选题', value: 'dan' },
                { label: '填空题', value: 'tian' },
                { label: '判断题', value: 'pan' }
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选项" v-if="question.type != 'tian' && question.type != 'pan'" prop="option">
          <el-input v-for="(item, index) in question.options" :key="item" v-model="item.option" placeholder="Please input"  style="margin: 5px 0;">
            <template #prepend>
              <div style="cursor:pointer;" :class="{answer: question.answer.indexOf(String.fromCharCode(65+index)) !== -1}" @click="setanswer(index)">{{ String.fromCharCode(65+index) }}</div>
            </template>
            <template #append>
              <el-button :icon="RemoveFilled" @click="deloption(index)"/>
            </template>
          </el-input>
          <el-button type="primary" style="margin-top: 5px" @click="addoption">添加选项</el-button>
        </el-form-item>
        <el-form-item label="选项" v-if="question.type != 'tian' && question.type == 'pan'" >
          <el-input v-for="(item, index) in ['对的', '错的']" :key="item" :value="item" disabled style="margin: 5px 0;">
            <template #prepend>
              <div style="cursor:pointer;" :class="{answer: question.answer.indexOf(String.fromCharCode(65+index)) !== -1}" @click="setanswer(index)">{{ String.fromCharCode(65+index) }}</div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="question.answer" :disabled="question.type !== 'tian'"/>
        </el-form-item>
        <el-form-item label="解析" prop="analysis">
          <el-input v-model="question.analysis" maxlength="50" placeholder="请输入解析" show-word-limit type="textarea"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="summit">提交</el-button>
        </el-form-item>
      </el-form>
  </el-dialog>
</template>

<script setup>
  import { useRouter } from 'vue-router'
  import { getgrouprecord, creategroup, gettestpaperlist, setquestion } from '@/api/question'

  import { ref, onBeforeMount, onBeforeUnmount } from 'vue'
  import { storeToRefs } from 'pinia'
  import { useStore } from '../../store'
  import { ElMessage } from 'element-plus'
  const store = useStore()
  const router = useRouter()

  const subjects = storeToRefs(store).subjectlist
  const subject = ref('历史')
  const types = ['练习', '组卷', '试卷']
  const type = ref('练习')
  const nums = [3, 5]
  const num = ref(3)
  const isTestpaper = ref(false)

  onBeforeMount(() => {
    // 获取科目列表
    store.initSubjectlist()
    subject.value = store.home.subject
    type.value = store.home.type
    num.value = store.home.num
    if (store.home.type === '试卷') {
      isTestpaper.value = true
    }
  })
  // 和小程序端有修改
  onBeforeUnmount(() => {
    store.home.subject = subject.value
    store.home.type = type.value
    store.home.num = num.value
  })
  // 选择做题类型
  const choosetype = (value) => {
    console.log(value)
    if (value === '试卷') {
      isTestpaper.value = true
    } else {
      isTestpaper.value = false
    }
  }

  const createNew = (isnew) => {
    if (type.value === '组卷') {
      if (isnew) {
        groupDialog.value = true
      } else {
        getgrouprecord({
          username: localStorage.getItem('token'),
          subject: subject.value
        }).then(res => {
          if (!res.isExist) {
            groupDialog.value = true
          } else {
            router.push({
              name: 'exercise',
              query: {
                subject: subject.value,
                type: type.value,
                num: num.value,
                isnew
              }
            })
          }
        })
      }
    } else {
      router.push({
        name: 'exercise',
        query: {
          subject: subject.value,
          type: type.value,
          num: num.value,
          isnew
        }
      })
    }
  }

  // 组卷部分
  const groupDialog = ref(false)
  const questionnum = ref({
    tiannum: 3,
    duonum: 3,
    dannum: 3,
    pannum: 3
  })
  const random = () => {
    questionnum.value.tiannum = Math.floor(Math.random() * 6)
    questionnum.value.pannum = Math.floor(Math.random() * 6)
    questionnum.value.dannum = Math.floor(Math.random() * 6)
    questionnum.value.duonum = Math.floor(Math.random() * 6)
  }
  const groupcreate = () => {
    creategroup({
      username: localStorage.getItem('token'),
      subject: subject.value,
      ...questionnum.value
    }).then(res => {
      const qnum = questionnum.value.tiannum + questionnum.value.duonum + questionnum.value.dannum + questionnum.value.pannum
      //   url: `/pages/exercise/exercise?type=组卷&subject=${subject.value}&num=${qnum}&isnew=0`
      router.push({
        name: 'exercise',
        query: {
          subject: subject.value,
          type: type.value,
          num: qnum,
          isnew: 0
        }
      })
    })
  }

  // 试卷部分
  const drawer = ref(false)
  const testpaperlist = ref([])
  const btnShow = ref([])
  const openDrawer = () => {
    gettestpaperlist({
      subject: subject.value
    }).then(res => {
      testpaperlist.value = res.testpaperlist
      // console.log(res.testpaperlist)
      const arr = []
      for (let i = 0; i < res.testpaperlist.length; i++) {
        arr.push(false)
      }
      btnShow.value = arr
      drawer.value = true
    })
  }
  const changeBtnShow = (index) => {
    btnShow.value[index] = !btnShow.value[index]
  }
  // 获取时间
  const getNowDate = (time) => {
    const date = new Date(time)
      const sign2 = ':'
      const year = date.getFullYear() // 年
      let month = date.getMonth() + 1 // 月
      let day = date.getDate() // 日
      let hour = date.getHours() // 时
      let minutes = date.getMinutes() // 分
      let seconds = date.getSeconds() // 秒
      // let weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
      // let week = weekArr[date.getDay()];
      // 给一位数的数据前面加 “0”
      if (month >= 1 && month <= 9) {
      month = '0' + month
      }
      if (day >= 0 && day <= 9) {
      day = '0' + day
      }
      if (hour >= 0 && hour <= 9) {
      hour = '0' + hour
      }
      if (minutes >= 0 && minutes <= 9) {
      minutes = '0' + minutes
      }
      if (seconds >= 0 && seconds <= 9) {
      seconds = '0' + seconds
      }
      return year + '-' + month + '-' + day + ' ' + hour + sign2 + minutes + sign2 + seconds
  }
  const testp = (item, isnew) => {
    // url: `/pages/exercise/exercise?type=${this.type}&subject=${this.subject}&time=${item.time}&isnew=${isnew}&testpaper=${item.testpaper}`,
    router.push({
      name: 'exercise',
      query: {
        subject: subject.value,
        type: type.value,
        num: num.value,
        time: item.time,
        isnew,
        testpaper: item.testpaper
      }
    })
  }

  // 编辑/新增问题表单弹窗
  const dialogVisible = ref(false)
  const question = ref({
    id: 0,
    title: '',
    subject: '',
    newsubject: '',
    type: 'dan',
    options: [],
    answer: '',
    analysis: '',
    isaddsubject: false
  })
  // 修改答案
  const setanswer = (index) => {
    const char = String.fromCharCode(65 + index)
    if (question.value.type === 'duo') {
      if (question.value.answer.indexOf(char) === -1) {
        const chars = question.value.answer.split('')
        let index = 0
        for (let i = 0; i < chars.length; i++) {
          // console.log(i, char, chars[i])
          if (i === 0 && char < chars[i]) {
            index = 0
            break
          } else if (i === chars.length - 1 && char > chars[i]) {
            index = i + 1
            break
          } else if (char < chars[i]) {
            index = i
            break
          }
        }
        // console.log(index)
        chars.splice(index, 0, char)
        question.value.answer = chars.join('')
      } else {
        question.value.answer = question.value.answer.replace(char, '')
      }
    } else {
      question.value.answer = char
    }
  }
  // 添加选项
  const addoption = () => {
    question.value.options.push({ option: '' })
  }
  // 删除选项
  const deloption = (index) => {
    question.value.options.splice(index, 1)
    // 修改答案
    question.value.answer = question.value.answer.replace(String.fromCharCode(65 + index), '')
    const chars = question.value.answer.split('')
    console.log(question.value.answer)
    for (let i = 0; i < chars.length; i++) {
      if (chars[i] > String.fromCharCode(65 + index)) {
        chars[i] = String.fromCharCode(chars[i].charCodeAt() - 1)
      }
    }
    question.value.answer = chars.join('')
  }
  // 改变题目类型
  const changeSelectType = (value) => {
    question.value.answer = ''
  }
  // const isfix = ref(false)
  // 自定义表单校验规则
  const validateOption = (rule, value, callback) => {
    const arr = question.value.options
    if (arr.length === 0) {
      return callback(new Error('不能没有选项'))
    } else {
      let flag = false
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].option === '') {
          flag = true
          break
        }
      }
      if (flag) {
        return callback(new Error('选项内容不能为空'))
      } else {
        return callback()
      }
    }
  }
  const rules = ref({
    title: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ],
    subject: [
      { required: true, message: '必须选择科目', trigger: 'blur' }
    ],
    newsubject: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ],
    option: [{ validator: validateOption, trigger: 'blur' }],
    analysis: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ],
    answer: [
      { required: true, message: '输入内容不能为空', trigger: 'blur' }
    ]
  })
  // 关闭/取消弹窗
  const closedialo = () => {
    question.value = {
      id: 0,
      title: '',
      subject: '',
      newsubject: '',
      type: 'dan',
      options: [],
      answer: '',
      analysis: '',
      isaddsubject: false
    }
    // isfix.value = false
    dialogVisible.value = false
  }
  // 提交
  const formRef = ref(null)
  const summit = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        setquestion(question.value).then(res => {
          // console.log(res)
          closedialo()
          ElMessage.success(res.msg)
        })
      } else {
        return false
      }
    })
  }
</script>

<style lang="less" scoped>
.box{
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 600px;
  background-color: #fff;
  padding: 30px;
  margin: 10vh auto;
  border: 1px solid rgba(0,0,0,.2);
  border-radius: 10px;

  .boxitem {
    display: flex;
    align-items: center;
    margin: 5px;
  }

  .btn {
    width: 300px;
    margin: 5px;
  }
}
.scrollbar-demo-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 10px;
  padding: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);

  .item {
    display: flex;
    justify-content: space-around;
    width: 100%;
    font-size: 15px;
    align-items: center;
  }
  .btnbox {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-top: 15px;
    button {
      width: 40%;
    }
  }
}

.answer {
    color: red;
    font-weight: bolder;
  }
</style>
